
package com.tianya.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * CSV操作 (导入和导出)
 */
@Slf4j
public class CSVUtils {

    public static boolean exportCsv(File file, List<String> dataList, String charset) {
        return exportCsv(file, dataList, charset, false);
    }

    public static boolean exportCsv(File file, List<String> dataList, String charset, boolean append) {
        log.info("Exporting CSV to file: {}", file.getAbsolutePath());
        try (FileOutputStream out = new FileOutputStream(file, append);
             OutputStreamWriter writer = new OutputStreamWriter(out, charset);
             BufferedWriter bw = new BufferedWriter(writer)) {
            if (dataList != null && !dataList.isEmpty()) {
                for (String data : dataList) {
                    bw.write(data);
                    bw.newLine(); // 使用newLine()替代"\r"，以适应跨平台的需求
                }
            }
            log.info("CSV export completed successfully.");
            return true;
        } catch (IOException e) {
            log.error("Error occurred during CSV export: ", e);
            return false;
        }
    }

    public static boolean exportCsv(File file, List<String> dataList) {
        return exportCsv(file, dataList, "GBK"); // 注意使用大写的"GBK"
    }

    public static List<String> importCsv(File file) {
        return importCsv(file, null, 0);
    }

    public static List<String> importCsv(File file, Integer offset, int limit) {
        List<String> dataList = new ArrayList<>();
        log.info("Importing CSV from file: {}", file.getAbsolutePath());
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            int index = 0;
            // Skip lines if offset is set
            while (offset != null && index < offset && (line = br.readLine()) != null) {
                index++;
            }
            // Read lines with limit consideration
            while ((line = br.readLine()) != null && (limit == 0 || index < offset + limit)) {
                dataList.add(line);
                index++;
            }
            log.info("CSV import completed successfully, {} lines read.", dataList.size());
        } catch (IOException e) {
            log.error("Error occurred during CSV import: ", e);
        }
        return dataList;
    }

    public static List<String> importCsvChar(String filePath, String charset) throws IOException {
        log.info("Importing CSV with specific charset from: {}", filePath);
        List<String> lines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charset))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
            log.info("CSV import with specific charset completed successfully.");
        }
        return lines;
    }
}